package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.service.ShoppingCartService;
import com.zrrd.reggie.util.BaseContext;
import com.zrrd.reggie.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart cart){
        return R.sucess(shoppingCartService.addCart(cart));
    }
    @GetMapping("/list")
    public R<List> list(){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId());
        wrapper.orderByDesc("create_time");
        return R.sucess(shoppingCartService.list(wrapper));
    }
    @DeleteMapping("/clean")
    public R<String> clean(){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId());
        return shoppingCartService.remove(wrapper)?R.sucess("删除成功"):R.error("删除失败");
    }
    @PostMapping ("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart cart){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        Long dishId = cart.getDishId();
        if(dishId!=null){
            wrapper.eq("dish_id",dishId);
        }else {
            wrapper.eq("setmeal_id",cart.getSetmealId());
        }
        ShoppingCart cartData = shoppingCartService.getOne(wrapper);
        cartData.setNumber(cartData.getNumber()-1);
        shoppingCartService.updateById(cartData);
        if(cartData.getNumber()<=0){

        }
        return R.sucess(cartData);
    }
}
